package com.simplesoftwares.client.library.composite;



import com.google.gwt.core.client.GWT;
import com.google.gwt.editor.client.Editor;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteHandler;
import com.google.gwt.user.client.ui.Hidden;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Hyperlink;
import com.slicktechnologies.client.userconfigurations.UserConfiguration;
import com.slicktechnologies.shared.common.helperlayer.DocumentUpload;


/**
 * The Class UploadComposite.Instance Comes with displayed file link and a delete button.
 *  State chart of component is such :
 *   Start : File Upload Widget is visible link is invisible Delete is invisible
 *   Doc uploaded : File Upload Widget is visible Link is visible Delete is visible
 *   Delete Pressed : Transition to Start
 *   
 *   Enable False : File Upload in disabled;Delete is non disabled;Link is Enabled(if present)
 *   Enable True : File Upload in Enabled;Delete is non Enabled;Link is Enabled
 *    
 *    To DO : Any how will have to explain Komal,so explain complete the documentation and explain her
 *    sequence diagram.Recent Changes are not tested.Tell komal to test.
 *   
 */
public class UploadReaderComposite  extends Composite implements SubmitCompleteHandler,ChangeHandler
,CompositeInterface,Editor<DocumentUpload>
{
	
     
	 /** The singleuploader. File Upload Widget*/
    protected  FileUpload singleuploader;
   
	 /** 
	  * hyperlink used to download the uploaded document
	  * */
    protected Hyperlink hyper;
	
     
	
	 
     
     /** 
      * FormPanel object to provide upload functionality
      * */
 	protected FormPanel panel;
    
     /** 
      * Horizontal Panel holds the UI 
      * */
     protected HorizontalPanel hp;
     
     /** .
      * cancel button ,this will clear the fileupload widget and hide the hyperlink
     *  this button will also set the Entity document upload part to null;
      *  */
     protected Button cancel;
     
     
     /** flags which restrict the file type to be uploaded. 
      * */
    protected boolean image,pdf,word,csv;
     
     
    
     
     
   
	 
	/**
	 * Instantiates a new my upload composite.
	 */
	
	/**
	  * On click of cancel the hyperlink and cancel should be hidden.When ever user 
	  * selects a file the file should be automatically uploaded.
	  * To do these things we apply handlers on cancel and file upload 
	  * widget.Also when submit completes the hyperlink should be visible 
      * with the url of download,We achieve this by applying submitComplete handler
	  * on panel
		 
	 */
	public UploadReaderComposite()
	
	{
		initalizevariables();
		image=false;
		initWidget(panel);
		addHandlers();
	}
	
	/**
	 * Initializes the cancel button ,hyperlink ,panel.
	 * Also sets encoding on form panel
	 */
	public void initalizevariables()
	{
		hp= new HorizontalPanel();
		singleuploader = new FileUpload();
		cancel = new Button("Delete");
		hyper = new Hyperlink();
		panel = new FormPanel();
		singleuploader.setName("upload");
		Hidden hidden=new Hidden();
		hidden.setValue(UserConfiguration.getCompanyId()+"");
		hidden.setName("companyId");
		hp.add(hidden);
		//Form panel settings
		panel.setEncoding(FormPanel.ENCODING_MULTIPART);
		panel.setMethod(FormPanel.METHOD_POST);	
        hp.add(singleuploader);
		
	    panel.setWidget(hp);
	}
	
	
	/**
	 * Creates the gui.
	 */
	public void createGui()
	{
		
		
		
		
		
	}
	
	
	/**
	 * Adds the {@link SubmitCompleteHandler} handler on panel 
	 * Adds the {@link ClickHandler} on the cancel button 
	 * Adds the {@link ChangeHandler} on <code>singleuploader</code>
	 */
	public void addHandlers()
	{
		panel.addSubmitCompleteHandler(this);
		
		singleuploader.addChangeHandler(this);
		
		
	}
	
	/**
	 * The method makes the widget to transit in START state
	 */
  
   /**
    * Downloads the file from corresponding link clicks.
    */
   
  
	
   /**
    * Actual file upload process code starts from this method.
    * Method checks for valid files. If file is valid then it sets the url
    * To Do : Understand the fake path thing
    */
   private void reactOnFileChange()
   {
	   String s=this.singleuploader.getFilename();
	   if(validFile(s))
		   setUrlAndSubmit();
	   System.out.println("Res--"+validFile(s));
   }
	


		  /* (non-Javadoc)
  		 * @see com.google.gwt.event.dom.client.ClickHandler#onClick(com.google.gwt.event.dom.client.ClickEvent)
  		 */
  		
	    
  		/**
  		 * Valid file.
  		 * @param s file path to be checked valid
  		 *
  		 * @return true, if uploaded file is not empty.
  		 * Or if the file type does not matches the valid file
  		 */ 
		
  		public boolean validFile(String s)
  		{
  			
  			if(s==null || s.trim().equals(""))
  				return false;
  			else
  			{
  				
  		        //Check for Image
  				if(image)
  				{
  				s=s.toLowerCase();
  				if(s.contains("jpeg")||s.contains("exif")||s.contains("tiff")
  						||s.contains("png")||s.contains("bmp"))
  					return true;
  				else
  					return false;
  			       
  			 }
  				
  				else if(csv)
  				{
  				s=s.toLowerCase();
  				if(s.contains("csv"))
  					return true;
  				else
  					return false;
  			       
  			 }
  				//check for csv
  				
  			
  			else
  			  return true;	
  			}
  		}
  		
  		/**
  		 * Sets the url and submit.
  		 * the methods uses blobservice to get the new url for upload and sets that
  		 * to form panel.
  		 * @param s 
  		 */
  		private void setUrlAndSubmit()
  		{
  			
  		   String url= GWT.getModuleBaseURL()+"attendenceupload";
  			panel.setAction(url);
			panel.submit();
  		}

  		/* (non-Javadoc)
  		 * @see com.simplesoftwares.client.library.composite.CompositeInterface#clear()
  		 */
  		@Override
  		public void clear() {
  			
  			panel.reset();
  			this.hyper.setVisible(false);
  			this.hyper.setHTML("");
  			cancel.setVisible(false);
  			
  		}


  		/* (non-Javadoc)
  		 * @see com.simplesoftwares.client.library.composite.CompositeInterface#validate()
  		 */
  		@Override
  		public boolean validate() {
  			
  			return true;
  		}
/* (non-Javadoc)
	 * @see com.simplesoftwares.client.library.composite.CompositeInterface#setEnable(boolean)
	 */
	@Override
	public void setEnable(boolean state)
	{
		singleuploader.setEnabled(state);
		if(hyper.getText().trim().equals(""))
			cancel.setVisible(false);
		else
		 cancel.setVisible(state);
		
	}


	//The method is called when submit is completed.WE set the hyperlink of uploaded url
	/* (non-Javadoc)
	 * @see com.google.gwt.user.client.ui.FormPanel.SubmitCompleteHandler#onSubmitComplete(com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent)
	 */
	/**
	 * Transit of app in Document Uploaded Mode
	 * To DO: If an error comes during upload process,system will behave unexpectedly ,please fix 
	 * At this point uploadDocument object is created.
	 * 
	 */
	@Override
	public void onSubmitComplete(SubmitCompleteEvent event) 
	{
		String[]splitaray=singleuploader.getFilename().split("\\\\");
		String savedfileName = splitaray[splitaray.length-1];
		//User has de selected the file do nothing
		hyper.setHTML(savedfileName);
		cancel.setVisible(true);
		hyper.setVisible(true);
		
		panel.reset();
	}


	/* (non-Javadoc)
	 * @see com.google.gwt.event.dom.client.ChangeHandler#onChange(com.google.gwt.event.dom.client.ChangeEvent)
	 */
	@Override
	public void onChange(ChangeEvent event) {
	
		
		reactOnFileChange();
		}
}

